<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search_input" type="text" placeholder="输入城市名或者拼音"/>
    </div>
    <div class="search_cont" v-show="keyword" ref="search">
      <ul>
        <li class="search_item border-bottom"
            v-for="item of list"
            :key="item.id"
            @click="cityClick(item.name)"
        >
          {{item.name}}
        </li>
        <li class="search_item border-bottom search_i" v-show="hasNoData">
          没有找到匹配项
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    cityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
      this.keyword = ''
      alert(city)
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const reslut = []
        for (let i in this.cities) {
          this.cities[i].forEach((val) => {
            if (val.spell.indexOf(this.keyword) > -1 || val.name.indexOf(this.keyword) > -1) {
              reslut.push(val)
            }
          })
        }
        this.list = reslut
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .search
    height: .72rem
    padding: 0 .1rem
    background: $bjColor
    .search_input
      box-sizing: border-box
      padding: 0 .1rem
      width: 100%
      height: .62rem
      line-height .62rem
      text-align center
      color: #666
      border-radius: .06rem
  .search_cont
    position: absolute
    top: 1.56rem
    left: 0
    right: 0
    bottom: 0
    z-index: 1
    overflow: hidden
    background: #eee
    .search_item
      line-height: .62rem
      padding-left: .2rem
      color: #666
      background: #fff
    .search_i
      text-align: center
</style>
